<template>
  <login-container> </login-container>
</template>
<script lang="ts" setup>
import type { AlipayRegisterData, AlipayLoginData, AlipayLoginResponse } from "@/api/alipay/types";
import { onMounted, ref } from "vue";
import { storageUtil } from "@/utils/storage";
import { useRoute, useRouter } from "vue-router";
import { useUserStoreHook } from "@/stores";
import { vueMetaEnv } from "@/settings";
import { loadSDK } from "@/utils/loadSDK";

import LoginContainer from "@/components/LoginContainer/index.vue";

const route = useRoute();
const router = useRouter();

const userStore = useUserStoreHook();

//注册登录
function alipayRegister(authCode: string) {
  userStore
    .alipayRegister({
      requestId: Math.random() * 10 + "",
      authCode: authCode
    } as AlipayRegisterData)
    .then((res: AlipayLoginResponse) => {
      if (res.status) {
        console.log("登录成功");
        let redirect = storageUtil.queryRedirect(route);
        router.push(redirect);
      } else {
        console.log("注册登录失败" + res.message);
      }
    });
}
// 支付宝静默授权
const getAuthCode = (scope: string) => {
  return new Promise((resolve, reject) => {
    window.ap?.getAuthCode({
      appId: vueMetaEnv.APP_ALIPAY_APPID,
      scopes: [scope],
      success: (res: any) => {
        resolve(res);
      },
      fail: () => {
        reject("登录失败");
      }
    });
  });
};

// code 换取token 登录
const alipayLogin = (authCode: string) => {
  userStore
    .alipayLogin({
      requestId: Math.random() * 10 + "",
      authCode
    } as AlipayLoginData)
    .then((res: AlipayLoginResponse) => {
      if (res.status) {
        let redirect = storageUtil.queryRedirect(route);
        router.push(redirect);
      } else {
        console.log("静默登录失败" + res.message);
        getAuthCode("auth_user").then((res: any) => {
          alipayRegister(res.authCode);
        });
      }
    });
};

onMounted(async () => {
  await loadSDK.AliSDK();
  getAuthCode("auth_base").then((res: any) => {
    alipayLogin(res.authCode);
  });
});
</script>
